package org.edu.modules.oa.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.sf.saxon.expr.TryCatch;
import org.apache.shiro.SecurityUtils;
import org.edu.common.system.vo.LoginUser;
import org.edu.modules.oa.entity.VeFileFilesEntity;
import org.edu.modules.oa.entity.VeOaTongxunluEntity;
import org.edu.modules.oa.entity.VeOaYinzhangEntity;
import org.edu.modules.oa.mapper.IVeFileFilesMapper;
import org.edu.modules.oa.mapper.IVeOaTongxunluMapper;
import org.edu.modules.oa.mapper.IVeOaYinzhangMapper;
import org.edu.modules.oa.service.IVeOaYinzhangService;
import org.edu.modules.oa.vo.VeOaYinzhangVo;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


@Service
public class VeOaYinzhangServiceImpl extends ServiceImpl<IVeOaYinzhangMapper, VeOaYinzhangEntity> implements IVeOaYinzhangService {

    @Resource
    private IVeFileFilesMapper veFileFilesMapper;

    @Resource
    private IVeOaYinzhangMapper veOaYinzhangMapper;

    //事务管理器
    @Resource(name="transactionManager")
    private DataSourceTransactionManager transactionManager;


    //添加印章信息，上传的图片信息
    @Override
    public Integer addYinzhang(VeOaYinzhangEntity veOaYinzhangEntity, VeFileFilesEntity veFileFilesEntity) {
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // 事物隔离级别，开启新事务，这样会比较安全些。
        TransactionStatus status = transactionManager.getTransaction(def); // 获得事务状态

        Integer result = 0;
        try {

            //添加图片信息
            veFileFilesMapper.insert(veFileFilesEntity);
            //添加印章
            veOaYinzhangEntity.setFileId(String.valueOf(veFileFilesEntity.getId()));
            veOaYinzhangMapper.insert(veOaYinzhangEntity);

            transactionManager.commit(status);
            result = 1;
            System.out.println("一起成功");
        } catch (Exception e) {
            e.printStackTrace();
            transactionManager.rollback(status);
            System.out.println("一起失败");
            result = 0;
        }
        return result;
    }

    //重复校验
    @Override
    public VeOaYinzhangEntity checkByName(VeOaYinzhangEntity veOaYinzhangEntity) {
        QueryWrapper<VeOaYinzhangEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("YinZhangName",veOaYinzhangEntity.getYinZhangName());
        if (veOaYinzhangEntity.getId() != null){
            queryWrapper.ne("ID",veOaYinzhangEntity.getId());
        }

        VeOaYinzhangEntity veOaYinzhangEntityll = veOaYinzhangMapper.selectOne(queryWrapper);
        return veOaYinzhangEntityll;
    }

    //查询印章表格信息
    @Override
    public HashMap<String, Object> showTable(VeOaYinzhangEntity veOaYinzhangEntity, Integer currentPage, Integer pageSize) {
        HashMap<String,Object> map = new HashMap<>();
        //创建分页的page
        IPage<VeOaYinzhangEntity> page = new Page<>(currentPage,pageSize);
        //创建查询的条件
        QueryWrapper<VeOaYinzhangEntity> queryWrapper = new QueryWrapper<>();
        //前台传来的条件
        if (veOaYinzhangEntity.getYinZhangName() != null && !veOaYinzhangEntity.getYinZhangName().equals("")){
            queryWrapper.eq("YinZhangName",veOaYinzhangEntity.getYinZhangName());
        }
        //印章类别
        if (veOaYinzhangEntity.getYinZhangLeiBie() != null && !veOaYinzhangEntity.getYinZhangLeiBie().equals("")){
            queryWrapper.eq("YinZhangLeiBie",veOaYinzhangEntity.getYinZhangLeiBie());
        }
        //未删除的
        queryWrapper.eq("is_deleted",0);
        //倒序
        queryWrapper.orderByDesc("create_time");

        //条件+分页查询
        page = veOaYinzhangMapper.selectPage(page,queryWrapper);
        List<VeOaYinzhangEntity> entityList = page.getRecords();

        List<VeOaYinzhangVo> voList = new ArrayList<>();

        // for循环把需要用的字段加到 导出集合里面去
        for(VeOaYinzhangEntity en:entityList){
            VeOaYinzhangVo vo = new VeOaYinzhangVo();
            //印章id
            vo.setId(en.getId());
            //印章名称
            vo.setYinZhangName(en.getYinZhangName());
            //印章类别
            vo.setYinZhangLeiBie(en.getYinZhangLeiBie());
            //印章密码
            vo.setYinZhangMiMa(en.getYinZhangMiMa());
            //创建人
            vo.setCreateUserName(en.getCreateUserName());
            //创建时间（时间类型转换成字符串）
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            vo.setCreateTime(formatter.format(en.getCreateTime()));
            //文件id --用来查文件信息
            vo.setFileId(en.getFileId());

            voList.add(vo);
        }
        //查询表格总行数
        int count = veOaYinzhangMapper.selectCount(queryWrapper);
        //把查出来的东西存到map里面去

        map.put("list",voList);
        map.put("count",count);

        return map;
    }


    //查印章对应的文件详情（文件id）
    @Override
    public VeFileFilesEntity showFileDetailByFileId(VeOaYinzhangEntity veOaYinzhangEntity) {
        QueryWrapper<VeFileFilesEntity> queryWrapper = new QueryWrapper<>();
        //用印章的文件id查文件信息
        queryWrapper.eq("id",veOaYinzhangEntity.getFileId());
        VeFileFilesEntity veFileFilesEntity = veFileFilesMapper.selectOne(queryWrapper);
        return veFileFilesEntity;
    }

    //修改印章信息，上传的图片信息
    @Override
    public Integer updateYinzhang(VeOaYinzhangEntity veOaYinzhangEntity, VeFileFilesEntity veFileFilesEntity) throws Exception {
        QueryWrapper<VeOaYinzhangEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID",veOaYinzhangEntity.getId());
        Integer result = 0;
        //文件不改时
        if (veFileFilesEntity == null){
            result = veOaYinzhangMapper.update(veOaYinzhangEntity,queryWrapper);
        }
        if (veFileFilesEntity != null){
            //在对应的文件id上修改文件
            QueryWrapper<VeFileFilesEntity> fileWrapper = new QueryWrapper<>();
            fileWrapper.eq("id",veOaYinzhangEntity.getFileId());
            result = veFileFilesMapper.update(veFileFilesEntity,fileWrapper);
            if (result != 0){
                result = veOaYinzhangMapper.update(veOaYinzhangEntity,queryWrapper);
            }

        }

        return result;
    }


    //逻辑删除（单/多）
    @Override
    public Integer deleteYinzhang(List<Long> ids) {
        Integer res = 0;
        res = veOaYinzhangMapper.deleteBatchIds(ids);
        return res;
    }

    //查询印章名称字段
    @Override
    public HashMap<String, Object> selectYinzhangName() {
        QueryWrapper<VeOaYinzhangEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("YinZhangName");
        queryWrapper.eq("YinZhangLeiBie","公共印章");
        List<VeOaYinzhangEntity> entityList = veOaYinzhangMapper.selectList(queryWrapper);
        HashMap<String,Object> map = new HashMap<>();
        map.put("list",entityList);
        return map;
    }

    //导出记录
    @Override
    public List<VeOaYinzhangVo> export(VeOaYinzhangEntity veOaYinzhangEntity) {
        //创建查询条件
        QueryWrapper<VeOaYinzhangEntity> queryWrapper = new QueryWrapper<>();
        //印章类别
        if (veOaYinzhangEntity.getYinZhangLeiBie() != null && !veOaYinzhangEntity.getYinZhangLeiBie().equals("")){
            queryWrapper.eq("YinZhangLeiBie",veOaYinzhangEntity.getYinZhangLeiBie());
        }
        //倒序
        queryWrapper.orderByDesc("create_time");
        //查询
        List<VeOaYinzhangEntity> entityList = veOaYinzhangMapper.selectList(queryWrapper);
        //集合voList是导出excel用的
        List<VeOaYinzhangVo> voList = new ArrayList<>();
        for (VeOaYinzhangEntity en:entityList){
            VeOaYinzhangVo vo = new VeOaYinzhangVo();
            //序号
            vo.setId(en.getId());
            //印章名称
            vo.setYinZhangName(en.getYinZhangName());
            //印章类别
            vo.setYinZhangLeiBie(en.getYinZhangLeiBie());
            //创建人
            vo.setCreateUserName(en.getCreateUserName());
            //创建时间
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            vo.setCreateTime(formatter.format(en.getCreateTime()));
            //用fileid查图片存储地址
            VeFileFilesEntity veFileFilesEntity = veFileFilesMapper.selectById(en.getFileId());
            vo.setSourceFile(veFileFilesEntity.getSourceFile());

            voList.add(vo);
        }

        return voList;
    }





}
